//
//  PhotoBrowserViewController.swift
//  zyqWeibo
//
//  Created by 张亚琼 on 15/7/5.
//  Copyright © 2015年 张亚琼. All rights reserved.
//

import UIKit
import FFAutoLayout
import SVProgressHUD

class PhotoBrowserViewController: UIViewController {
    // 希望在modal出来的时候就已经接收到传入的数据，所以重构init方法
    init(urls:[NSURL],index:Int) {
        imageUrls = urls
        imageIndex = index
        super.init(nibName: nil, bundle: nil)
//        print("哎呀哎呀\(imageIndex)")
    }

    required init(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func save() {
//        print("点击了save按钮")
        // 获取cell
        let indexPath = collectionView.indexPathsForVisibleItems().last
        let cell = collectionView.cellForItemAtIndexPath(indexPath!) as! PhotoBrowserCell
        // 获取cell中的图片
        let image = cell.imageView.image
        // 把图片保存到相册--回调方法的格式是固定的
        UIImageWriteToSavedPhotosAlbum(image!, self, "image:didFinishSavingWithError:contextInfo:", nil)
    }
    
    //回调函数固定格式  - (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo;
    // 转换为swift格式：image(image:UIImage,didFinishSavingWithError error:NSError,contextInfo:AnyObject);
    func image(image:UIImage,didFinishSavingWithError error:NSError?,contextInfo:AnyObject){
//        print("回调函数")
        if error != nil {
            SVProgressHUD.showErrorWithStatus("保存出错")
        }else {
            SVProgressHUD.showSuccessWithStatus("保存成功")
        }
    }
    
    func close() {
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    //
    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        prepareLayout()
        
        // 用户点击了哪个图片，上来显示的就该是哪个
        let indexPath = NSIndexPath(forItem: imageIndex!, inSection: 0)
        collectionView.scrollToItemAtIndexPath(indexPath, atScrollPosition: UICollectionViewScrollPosition.CenteredHorizontally, animated: false)
    }
    
    // 准备layout
    func prepareLayout() {
        layout.itemSize = view.bounds.size
        layout.minimumInteritemSpacing = 0
        layout.minimumLineSpacing = 0
        collectionView.pagingEnabled = true
        layout.scrollDirection = UICollectionViewScrollDirection.Horizontal
    }
    
    override func loadView() {
        view = UIView(frame: UIScreen.mainScreen().bounds)
        view.addSubview(collectionView)
        
        view.addSubview(saveButton)
        view.addSubview(closeButton)
        
        collectionView.ff_Fill(view)
        saveButton.ff_AlignInner(ff_AlignType.BottomLeft, referView: view, size: CGSize(width: 50, height: 20),offset:CGPoint(x: 12, y: -12))
        closeButton.ff_AlignInner(ff_AlignType.BottomRight, referView: view, size: CGSize(width: 50, height: 20), offset: CGPoint(x: -12, y: -12))
        saveButton.addTarget(self, action: "save", forControlEvents: UIControlEvents.TouchUpInside)
        closeButton.addTarget(self, action: "close", forControlEvents: UIControlEvents.TouchUpInside)
        
        // 准备collectionView
        prepareCollectionView()
    }
    
    private func prepareCollectionView() {
        collectionView.dataSource = self
        collectionView.delegate = self
        collectionView.registerClass(PhotoBrowserCell.self, forCellWithReuseIdentifier: YQPhotoBrowserReuseIdentifier)
    }

    //
    private var imageUrls:[NSURL]?
    private var imageIndex:Int?
    
    //MARK: 懒加载
    lazy private var layout = UICollectionViewFlowLayout()
    lazy private var collectionView:UICollectionView = UICollectionView(frame: CGRectZero, collectionViewLayout: self.layout)
    // 按钮
    lazy var saveButton:UIButton = UIButton(title: "保存", fontSize: 14)
    lazy var closeButton:UIButton = UIButton(title: "关闭", fontSize: 14)
    
}

//MARK: 类扩展
private let YQPhotoBrowserReuseIdentifier = "YQPhotoBrowserReuseIdentifier"
extension PhotoBrowserViewController:UICollectionViewDataSource,UICollectionViewDelegate {
    //MARK: 数据源方法
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return imageUrls?.count ?? 0
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(YQPhotoBrowserReuseIdentifier, forIndexPath: indexPath) as! PhotoBrowserCell
        cell.backgroundColor = UIColor.redColor()
        cell.imageUrl = imageUrls![indexPath.item]
        return cell
    }
}
